//
//  WDLocalizable.swift
//  WDLocalizable
//
//  Created by gupengling on 2021/7/14.
//

import UIKit

@discardableResult
public func KLocalizable(_ key: String, _ table: String? = nil) -> String {
    return WDLocalizable.localizedString(withKey: key, tableName: table)
}

@discardableResult
public func KLocalizableBundle(_ key: String, _ bundle: Bundle, _ table: String = "Localizable") -> String {
    return WDLocalizable.localizedString(withKey: key, bundle: bundle, tableName: table)
}

//MARK: - 本地化配置
public class WDLocalizable: NSObject {

    /// 默认语言
    private var _currentLanguage: WDLocalizableLanguage = .zh_Hans
    private var currentLanguage: WDLocalizableLanguage {
        set {
            if newValue != _currentLanguage {
                _currentLanguage = newValue
                UserDefaults.standard.set(_currentLanguage.rawValue, forKey: "CurrentLanguage")
                UserDefaults.standard.synchronize()
            }
        }
        get {
            if let type = WDLocalizableLanguage(rawValue: UserDefaults.standard.integer(forKey: "CurrentLanguage")),
               type != .none {
                _currentLanguage = type
            }
            return _currentLanguage
        }
    }
    /// lproj 所在的 Bundle
    private var bundle: Bundle = Bundle.main
    /// 本地化文件名称(默认: Localizable)
    private var tableName: String = "Localizable"
    
    private static let instance = WDLocalizable()
    @discardableResult
    static func shared() -> WDLocalizable {
        return instance
    }
    
    private override init() {}
    
    deinit {}
}

extension WDLocalizable {

    /// 获取系统语言
    /// - Returns: 返回当前语言
    @objc public static func getLocalCurrentLanguage() -> String {
        let languages = Locale.preferredLanguages
        if let currentLanguage = languages.first,
           !currentLanguage.isEmpty,
           let con = currentLanguage.components(separatedBy: "-").first,
           !con.contains("zh") {
            return con
        }
        return "zh-ch"
    }
    
    /// @说明 设置本地化语言类型
    /// @参数 language:   本地化语言类型
    /// @参数 tableName:  本地化语言文件名称(默认: Localizable)
    /// @返回 void
    @objc public static func setLanguage(_ language: WDLocalizableLanguage, tableName: String = "Localizable") {
        
        /// 保存当前语言
        WDLocalizable.shared().currentLanguage = language
        
        /// 初始化 lproj
        var lproj: String = "Base"
        
        /// 语言跟随系统，获取 lproj 名称
        if language == .follow {
            /// 获取系统语言名称("en", "zh-Hans", ...)中的第一个
            var systemLanguage: String = ""
            let appleLanguages: Any? = UserDefaults.standard.value(forKey: "AppleLanguages")
            if appleLanguages != nil && appleLanguages is [String] {
                let languages: [String] = appleLanguages as! [String]
                if !languages.isEmpty {
                    systemLanguage = languages[0]
                }
            }
            
            /// 根据系统语言配置 lproj 名称
            if systemLanguage.contains("en") {
                lproj = WDLocalizableLanguage.en.lproj
            } else if systemLanguage.contains("Hans-CN") {
                lproj = WDLocalizableLanguage.zh_Hans.lproj
            } else if systemLanguage.contains("Hant-CN") {
                lproj = WDLocalizableLanguage.zh_Hans.lproj
            } else if systemLanguage.contains("HK") {
                lproj = WDLocalizableLanguage.zh_Hant_KH.lproj
            } else if systemLanguage.contains("TW") {
                lproj = WDLocalizableLanguage.zh_Hant_TW.lproj
            } else if systemLanguage.contains("fr") {
                lproj = WDLocalizableLanguage.fr.lproj
            } else if systemLanguage.contains("de") {
                lproj = WDLocalizableLanguage.de.lproj
            } else if systemLanguage.contains("it") {
                lproj = WDLocalizableLanguage.it.lproj
            } else if systemLanguage.contains("ja") {
                lproj = WDLocalizableLanguage.ja.lproj
            } else if systemLanguage.contains("ko") {
                lproj = WDLocalizableLanguage.ko.lproj
            } else if systemLanguage.contains("pt") {
                lproj = WDLocalizableLanguage.pt_PT.lproj
            } else if systemLanguage.contains("ru") {
                lproj = WDLocalizableLanguage.ru.lproj
            } else if systemLanguage.contains("es") {
                lproj = WDLocalizableLanguage.es.lproj
            } else if systemLanguage.contains("nl") {
                lproj = WDLocalizableLanguage.nl.lproj
            } else if systemLanguage.contains("th") {
                lproj = WDLocalizableLanguage.th.lproj
            } else if systemLanguage.contains("ar") {
                lproj = WDLocalizableLanguage.ar.lproj
            }
        } else {
            /// 语言非跟随系统，获取 lproj 名称
            lproj = language.lproj
        }
        
        /// 获取 lproj 所在的 Bundle
//        if let path = Bundle.main.path(forResource: lproj, ofType: nil) {
//            WDLocalizable.shared().bundle = Bundle(path: path)!
//        } else {
        let tmpBundle = Bundle(for: WDLocalizable.self)
        if let url = tmpBundle.url(forResource: "WDLocalizable", withExtension: "bundle"),
           let tmp = Bundle(url: url),
           let p = tmp.path(forResource: lproj, ofType: ""),
           let b = Bundle(path: p) {
            WDLocalizable.shared().bundle = b
        }
//        }
        
        /// 本地化语言文件名称(如默认系统的: Localizable.strings 文件的名称 Localizable)
        WDLocalizable.shared().tableName = tableName
    }
    

    @discardableResult
    @objc public static func currentLanguage() -> WDLocalizableLanguage {
        return WDLocalizable.shared().currentLanguage
    }

    /// @说明 获取对应的本地化语言，如果没有对应本地化文件则直接返回Key
    /// @参数 key:    本地化语言对应的Key值
    /// @返回 String
    @discardableResult
    @objc public static func localizedString(withKey key: String) -> String {
        return localizedString(withKey: key, tableName: nil)
//        return localizedString(withKey: key,
//                               bundle: WDLocalizable.shared().bundle,
//                               tableName: WDLocalizable.shared().tableName)
//        if key.isEmpty {
//            return key
//        }
//
//        /// 获取并返回对应的本地化语言
//        let bundle: Bundle = WDLocalizable.shared().bundle
//        let tableName: String = WDLocalizable.shared().tableName
//        return NSLocalizedString(key, tableName: tableName, bundle: bundle, value:"", comment: "")
    }

    @discardableResult
    @objc public static func localizedString(withKey key: String, tableName: String?) -> String {
        return localizedString(withKey: key,
                               bundle: WDLocalizable.shared().bundle,
                               tableName: tableName ?? WDLocalizable.shared().tableName)
    }

    @discardableResult
    @objc public static func localizedString(withKey key: String,
                                             bundle: Bundle = Bundle.main,
                                             tableName: String = "Localizable") -> String {
        if key.isEmpty {
            return key
        }

        /// 获取并返回对应的本地化语言
        let bundle: Bundle = bundle
        let tableName: String = tableName
        return NSLocalizedString(key, tableName: tableName, bundle: bundle, value:"", comment: "")
    }
}
